import React, { useState, useEffect } from 'react';
import { Line } from '@ant-design/charts';

const handle = (property) => {
  return function(a,b){
      const val1 = a[property];
      const val2 = b[property];
      return val1 - val2;
  }
}

const LineDemo: React.FC = ({ growthBzData, growthData,babyData }) => {
  const [data, setData] = useState([]);
  let ref;
  useEffect(() => {
    asyncFetch();
  }, [growthBzData, growthData]);
  const asyncFetch = () => {
    var datas = [];
    {
      growthData.forEach(element => {
        var obj = {
          ageWeek: babyData.gweek < 40 ? element.ageWeek : element.ageMonth,
          value: element.headCirc,
          category: '宝宝'
        }
        datas.push(obj)
      });
      growthBzData.forEach(element => {
        var obj = {
          ageWeek: element.gestationalAge,
          value: element.headThree,
          category: '最小值'
        }
        datas.push(obj);
        obj = {
          ageWeek: element.gestationalAge,
          value: element.headNintySeven,
          category: '最大值'
        }
        datas.push(obj)
        obj = {
          ageWeek: element.gestationalAge,
          value: element.headFifty,
          category: '标准值'
        }
        datas.push(obj)
      });      
      setData(datas.sort(handle('ageWeek')))
    }

  };
  var config = {
    data: data,
    padding: 'auto',
    xField: 'ageWeek',
    yField: 'value',
    seriesField: 'category',
    yAxis: {
      label: {
        formatter: function formatter(v) {
          return v + 'cm';
        },
      },
      min:15,
      nice: true,
    },
    xAxis: {
      label: {
        formatter: function formatter(v) {
          return v + (babyData.gweek < 40 ? '周' : '月');
        },
      },
    },
    color: function color(_ref) {
      var type = _ref.category;
      return type === '宝宝' ? 'red' : type === '标准值'?'green' : '#ccc';
    },
    lineStyle: function lineStyle(_ref2) {
      var type = _ref2.category;
      if (type != '宝宝') {
        return {
          lineDash: [1, 5],
          lineWidth: 2,
          strokeOpacity: 1,
        };
      }
      else
        return {
          opacity: 0.5,
          shadowColor: 'gray',
          shadowBlur: 3,
        };
    },
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 3000,
      },
    },
  };

  return <Line {...config} chartRef={(chartRef) => (ref = chartRef)} />;
};

export default LineDemo;